import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class ShellExecUtil {

    public interface MsgCallback {
        void invoke(String msg);
    }

    public static void run(MsgCallback msgCallback, String... command) {
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        //processBuilder.command(command);
        //将标准输入流和错误输入流合并，通过标准输入流读取信息
        processBuilder.redirectErrorStream(true);
        try {
            //启动进程
            Process start = processBuilder.start();
            //获取输入流
            InputStream inputStream = start.getInputStream();
            //转成字符输入流
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            int len = -1;
            char[] c = new char[1024];
            StringBuilder outputString = new StringBuilder();
            //读取进程输入流中的内容
            while ((len = inputStreamReader.read(c)) != -1) {
                String s = new String(c, 0, len);
                outputString.append(s);
            }
            msgCallback.invoke(outputString.toString());
            System.out.print(outputString);
            inputStream.close();
        } catch (IOException e) {
            msgCallback.invoke(e.getMessage());
            e.printStackTrace();
        }
    }
}
